import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Form, Input, Modal, TreeSelect, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import AddFrom from './components/AddForm';
import type { AdminItem, UpdateAdminIdentifyBean } from './data';
import {
  deleteAdmin,
  editAdminIdentify,
  queryAdminList,
  queryPositionByDep,
  updateAdminInfo,
  updateAdminPwd,
} from './service';
import { useModel } from 'umi';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import UpdataIdentity from './components/UpdataIdentity';
import { SUCCESS_CODE } from '@/utils/request';
import UpdateAdminInfoForm from './components/UpdateAdminInfoForm';
import { queryDepartment } from '../Department/service';

const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const {
    'ADMIN.REGISTER': register,
    '	ADMIN.UPDATE': update,
    'ADMIN.DELETE': Delete,
    'ADMIN.CHANGE.IDENTIFY': change,
  } = currUser;
  // const isAdmin = currUser?.type === 1;

  const [updateInfoVisible, setUpdateInfoVisible] = useState<boolean>(false);
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [clickItemId, setClickItemId] = useState<string>('');
  const [passwordVisible, setPasswordVisible] = useState<boolean>(false);
  const [clickItem, setClickItem] = useState<any>();
  const [editIdentifyVisible, setEditIdentifyVisible] = useState<boolean>(false);

  const [treeDate, setTreeDate] = useState<any[]>([]);
  const [positionData, setPositionData] = useState<any[]>();
  const [twoTreeDisplay, setTwoTreeDisplay] = useState(true);
  const [departmentId, setDepartmentId] = useState<string | undefined>();
  const [positionId, setPositionId] = useState<string | undefined>();

  function convertData(data: { id: any; name: any; next_level: string | any[] }) {
    const node = {
      value: data.id,
      title: data.name,
      children: [] as any,
    };
    if (data.next_level && data.next_level.length > 0) {
      for (let i = 0; i < data.next_level.length; i++) {
        const child = convertData(data.next_level[i]);
        node.children.push(child);
      }
    }
    return node;
  }

  useEffect(() => {
    queryDepartment().then((res) => {
      if (res && res.code == 0) {
        const data = res?.data;
        const convert = [];
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            convert.push(convertData(data[i]));
          }
          setTreeDate(convert);
        }
      }
    });
  }, []);

  const actionRef = useRef<ActionType>();

  const handleRemove = async (id: string) => {
    const hide = message.loading('正在删除');

    const res = await deleteAdmin(id);

    if (res.code == 0) {
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } else {
      hide();
      message.error(`${res.message}`);
      return false;
    }
  };

  const editIdentifyEvent = async (values: UpdateAdminIdentifyBean) => {
    const res = await editAdminIdentify(values);
    if (res.code === SUCCESS_CODE) {
      message.success('修改成功');
      setEditIdentifyVisible(false);
      actionRef.current?.reload();
    } else {
      message.error(res.message || '修改失败');
    }
  };

  const editInfoEvent = async (values: any) => {
    const res = await updateAdminInfo({
      id: values.id,
      name: values.name,
      account: values.account,
      mobile: values.mobile,
    });
    if (res.code === SUCCESS_CODE) {
      message.success('修改成功');
      setUpdateInfoVisible(false);
      actionRef.current?.reload();
    } else {
      message.error(res.message || '修改失败');
    }
  };

  const columns: ProColumns<AdminItem>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      ellipsis: true,
    },
    {
      title: '管理员名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '管理员账号',
      dataIndex: 'account',
      ellipsis: true,
      search: false,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      ellipsis: true,
    },
    {
      title: '部门',
      dataIndex: 'department_name',
      ellipsis: true,
      renderFormItem: () => (
        <TreeSelect
          showSearch
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="请选择部门"
          allowClear
          autoClearSearchValue
          treeDefaultExpandAll
          onChange={(newValue, _labelList) => {
            if (newValue) {
              setDepartmentId(newValue);
              queryPositionByDep(newValue).then((res) => {
                if (res && res.code == 0) {
                  const data = res?.data;
                  const convert = [];
                  if (data && data.length > 0) {
                    for (let i = 0; i < data.length; i++) {
                      convert.push(convertData(data[i]));
                    }
                    setPositionData(convert);
                    setTwoTreeDisplay(false);
                  }
                }
              });
            }
          }}
          treeData={treeDate}
        />
      ),
    },
    {
      title: '职位',
      dataIndex: 'position_name',
      ellipsis: true,
      renderFormItem: () => (
        <TreeSelect
          disabled={twoTreeDisplay}
          autoClearSearchValue
          showSearch
          onChange={(newValue) => {
            setPositionId(newValue);
          }}
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="请选择职位"
          allowClear
          treeDefaultExpandAll
          treeData={positionData}
        />
      ),
    },
    {
      title: '上级管理员',
      dataIndex: 'belong',
      ellipsis: true,
      render: (_, record) => {
        return record.belong_name;
      },
      renderFormItem: () => {
        return <ProFormText placeholder={'请输入上级管理员id'}></ProFormText>;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '身份管理',
      dataIndex: 'roles',
      search: false,
      ellipsis: true,
      render: (_, record) => {
        return (
          <>
            {change && (
              <a
                style={{ marginRight: 20 }}
                onClick={() => {
                  setEditIdentifyVisible(true);
                  setClickItem(record);
                  setClickItemId(record.id);
                }}
              >
                修改身份
              </a>
            )}
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'options',
      hideInSearch: true,
      ellipsis: true,
      render: (_, record) => {
        const onClickUpdateInfo = () => {
          setUpdateInfoVisible(true);
          setClickItem(record);
        };
        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除管理员 ${id}`,
            content: (
              <>
                <Divider />
                <p>确认要删除管理员</p>
                <span style={{ fontWeight: 'bolder' }}>{name}</span>
                &nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove(id);
            },
            centered: true,
            width: '30vw',
            style: { height: '15vw' },
          });
        };
        return (
          <div>
            {update && <a onClick={onClickUpdateInfo}>修改信息</a>}
            <Divider type="vertical" />
            <a
              onClick={() => {
                setPasswordVisible(true);
                setClickItemId(record.id);
              }}
            >
              修改密码
            </a>
            <Divider type="vertical" />
            {Delete && <a onClick={onClickRemove}>删除</a>}
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<AdminItem>
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        onReset={() => {
          setDepartmentId(undefined);
          setPositionId(undefined);
          setTwoTreeDisplay(true);
        }}
        headerTitle="管理员列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        toolBarRender={() => [
          <>
            {register && (
              <Button key={''} type="primary" onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined /> 添加
              </Button>
            )}
          </>,
        ]}
        tableAlertRender={() => false}
        rowSelection={false}
        request={async (params = {}) => {
          params.department_id = departmentId;
          params.position_id = positionId;
          const res = await queryAdminList(params);
          return res;
        }}
        columns={columns}
      />
      {addModalVisible && (
        <AddFrom
          modalVisible={addModalVisible}
          reloadFunc={() => {
            actionRef.current?.reload();
          }}
          onCancel={() => handleAddModalVisible(false)}
        />
      )}
      {clickItem && editIdentifyVisible && (
        <UpdataIdentity
          item={clickItem}
          modalVisible={editIdentifyVisible}
          onSubmit={editIdentifyEvent}
          onCancel={() => setEditIdentifyVisible(false)}
          visibleHandler={() => setEditIdentifyVisible(false)}
        />
      )}
      {clickItem && updateInfoVisible && (
        <UpdateAdminInfoForm
          admin={clickItem}
          modalVisible={updateInfoVisible}
          onSubmit={editInfoEvent}
          onCancel={() => setUpdateInfoVisible(false)}
          visibleHandler={() => setUpdateInfoVisible(false)}
        />
      )}
      <Modal
        footer={null}
        open={passwordVisible}
        centered
        title="修改密码"
        destroyOnClose
        style={{ marginBottom: 100 }}
        onCancel={() => {
          setPasswordVisible(false);
        }}
      >
        <ProForm
          layout="horizontal"
          onFinish={async (value) => {
            const values = {
              pwd: value.password,
              id: clickItemId,
            };
            const hide = message.loading('正在修改');
            const res = await updateAdminPwd(values);

            hide();
            if (res.code === 0) {
              message.success(`${res.message}`);
              setPasswordVisible(false);
              actionRef.current?.reload();
              return true;
            } else {
              message.error(`${res.message}`);
              return false;
            }
          }}
        >
          <Form.Item
            name="password"
            label="新密码"
            rules={[{ required: true, message: '新密码不能为空' }]}
          >
            <Input type="password" />
          </Form.Item>
        </ProForm>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default TableList;
